package com.flyshop.core.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.flyshop.common.utils.FileUtils;
import com.flyshop.common.utils.ImageUtil;
import com.flyshop.common.utils.lucbir.features.PHash;
import com.flyshop.common.utils.lucbir.index.LucbirIndexer;
import com.flyshop.core.base.BaseController;
import com.flyshop.core.entity.DataVo;
import com.flyshop.core.entity.UpImgMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * 开发公司：97560.com<br/>
 * 版权：97560.com<br/>
 * <p>
 * 
 * 图片上传Controller
 * 
 * <p>
 * 
 * 区分　责任人　日期　　　　说明<br/>
 * 创建　孙开飞　2017年5月25日 　<br/>
 * <p>
 * *******
 * <p>
 * 
 * @author sun-kaifei
 * @email admin@97560.com
 * @version 1.0,2017年7月25日 <br/>
 * 
 */
@Controller
public class UpLoadController extends BaseController {

	/*
	 * 图片命名格式
	 */
	private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMddHHmmss";

	/*
	 * 上传图片文件夹
	 */
	private static final String UPLOAD_PATH = "upload/usertmp/";

	/*
	 * 上传图片
	 */
	@RequestMapping(value = "/member/upload")
	public void uplodaImg(@RequestParam("upload") MultipartFile file,
			HttpServletRequest request, 
			HttpServletResponse response){
		try {

			String proName = "./uploadfiles/";
			String path = proName + "upload/usertmp/";
			PrintWriter out = response.getWriter();
			String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");
			String fileName = file.getOriginalFilename();
			String uploadContentType = file.getContentType();
			String expandedName = "";
			if ("image/jpeg".equals(uploadContentType)
					|| uploadContentType.equals("image/jpeg")) {
				// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
				expandedName = ".jpg";
			} else if ("image/png".equals(uploadContentType) || "image/x-png".equals(uploadContentType)) {
				// IE6上传的png图片的headimageContentType是"image/x-png"
				expandedName = ".png";
			} else if ("image/gif".equals(uploadContentType)) {
				expandedName = ".gif";
			} else if ("image/bmp".equals(uploadContentType)) {
				expandedName = ".bmp";
			} else {
				out.println("<script type=\"text/javascript\">");
				out.println("window.parent.CKEDITOR.tools.callFunction("
						+ CKEditorFuncNum + ",'',"
						+ "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');");
				out.println("</script>");
				return;
			}
			if (file.getSize() > 1024 * 1024 * 2) {
				out.println("<script type=\"text/javascript\">");
				out.println("window.parent.CKEDITOR.tools.callFunction("
						+ CKEditorFuncNum + ",''," + "'文件大小不得大于2M');");
				out.println("</script>");
				return;
			}
			File dirFile = new File(path);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
			fileName = df.format(new Date()) + expandedName;
			file.transferTo(new File(path + "/" + fileName));
			int port=request.getServerPort();
			//System.out.println("++++11111++++:"+port);
			String portstr="";
			if(port>0){
				portstr+=":"+port;
			}
			out.println("<script type=\"text/javascript\">");
			out.println("window.parent.CKEDITOR.tools.callFunction("
					+ CKEditorFuncNum + ",'" +"http://"+ request.getServerName()+portstr+"/upload/usertmp/" + fileName
					+ "','')");
			out.println("</script>");
			return;
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/admin/upload", method = RequestMethod.POST)
    public DataVo uploadFile(HttpServletRequest request, ModelMap modelMap){
		DataVo data = DataVo.failure("操作失败");
		UpImgMsg msg=new UpImgMsg();
		String filePath = UPLOAD_PATH;
        String filePathUrl="./uploadfiles/"+filePath;
        try {
        	UpImgMsg file = ImageUtil.uploadFile(request, filePath,filePathUrl);
            if(file.getImgurl()==null){
            	msg.setCode(-1);
            	msg.setImgurl(null);
            	msg.setFilesize(file.getFilesize());
            	msg.setMsg("上传失败");
            	return DataVo.success("上传失败", msg);
            }else{
            	msg.setCode(0);
            	msg.setImgurl("/"+file.getImgurl());
            	msg.setFilesize(file.getFilesize());
            	msg.setMsg("上传成功");
            	return DataVo.success("上传成功", msg);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch(Exception ex){
            ex.printStackTrace();
        }
        return data;
    }
}